<template>
  <!-- 新增Banking接收账户列表 -->
  <div class="banking-receive-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>Banking接收账户列表</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="receiveSearchForm" inline>
          <el-form-item label="转出代理商">
            <el-select
              v-model="receiveSearchForm.FromMerchantId"
              placeholder="请选择转出代理商"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in merchantIdOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="转入代理商">
            <el-select
              v-model="receiveSearchForm.ToMerchantId"
              placeholder="请选择转入代理商"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in merchantIdOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上游平台配置">
            <el-select
              v-model="receiveSearchForm.UpstreamPlatformId"
              placeholder="请选择上游平台配置"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in upstreamPlatformOptions"
                :key="item.Id"
                :label="item.Code"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleReceiveSearch">搜索</el-button>
            <el-button @click="handleReceiveReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- Banking接收账户表格 -->
      <el-table 
        :data="receiveList" 
        v-loading="receiveLoading"
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="Id" label="id" width="80" />
        <el-table-column prop="BeneficiaryId" label="账户uuid" show-overflow-tooltip>
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.ProductId" placement="top">
                <span class="text-ellipsis">{{ scope.row.BeneficiaryId }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.BeneficiaryId, '账户uuid')"
                class="copy-btn"
                v-if="scope.row.BeneficiaryId"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="UpstreamPlatformId" label="上游平台id" show-overflow-tooltip/>
        <el-table-column prop="UpstreamPlatform" label="上游平台代码" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.UpstreamPlatform?.Code }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="FromMerchantId" label="转出商户id" show-overflow-tooltip/>
        <el-table-column prop="FromMerchant" label="转出商户名称" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.FromMerchant?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ToMerchantId" label="转入商户id" show-overflow-tooltip/>
        <el-table-column prop="ToMerchant" label="转入商户名称" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.ToMerchant?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="CreatedAtString" label="创建时间" width="180" show-overflow-tooltip/>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleDeleteReceive(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="receiveCurrentPage"
          v-model:page-size="receivePageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="receiveTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleReceiveSizeChange"
          @current-change="handleReceiveCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import { bankingReceiveList, deleteUpBeneficiary } from '@/api/merchant'
import { merchantList, upstreamPlatformList } from '@/api/selectList'

const upstreamPlatformOptions = ref([])

// 接收账户列表相关数据
const receiveLoading = ref(false)
const receiveList = ref([])
const receiveCurrentPage = ref(1)
const receivePageSize = ref(10)
const receiveTotal = ref(0)

const merchantIdOptions = ref([])
// 接收账户搜索表单
const receiveSearchForm = reactive({
  FromMerchantId: null,
  ToMerchantId: null,
  UpstreamPlatformId: null
})

// 获取商户下拉选项
const getMerchantIdOptions = async () => {
  try {
    const res = await merchantList()
    if (res.code === 200) {
      merchantIdOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 获取上游平台下拉选项
const getUpstreamPlatformOptions = async () => {
  try {
    const res = await upstreamPlatformList()
    if (res.code === 200) {
      upstreamPlatformOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 获取接收账户列表
const getReceiveList = async () => {
  receiveLoading.value = true
  try {
    const res = await bankingReceiveList({
      Page: receiveCurrentPage.value,
      PageSize: receivePageSize.value,
      ...receiveSearchForm
    })
    if (res.code === 200) {
      receiveList.value = res.data?.List || []
      receiveTotal.value = res.data?.Total
    } else {
      ElMessage.error('获取接收账户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取接收账户列表失败')
  } finally {
    receiveLoading.value = false
  }
}

// 接收账户搜索
const handleReceiveSearch = () => {
  receiveCurrentPage.value = 1
  getReceiveList()
}

// 重置接收账户搜索
const handleReceiveReset = () => {
  Object.assign(receiveSearchForm, {
    FromMerchantId: null,
    ToMerchantId: null,
    UpstreamPlatformId: null
  })
  receiveCurrentPage.value = 1
  getReceiveList()
}

// 接收账户分页大小改变
const handleReceiveSizeChange = (size) => {
  receivePageSize.value = size
  getReceiveList()
}

// 接收账户当前页改变
const handleReceiveCurrentChange = (page) => {
  receiveCurrentPage.value = page
  getReceiveList()
}

// 删除接收账户
const handleDeleteReceive = (row) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteUpBeneficiary({ Id: row.Id })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getReceiveList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 生命周期
onMounted(() => {
  getReceiveList()
  getMerchantIdOptions()
  getUpstreamPlatformOptions()
})

// 复制功能
const handleCopy = async (text, fieldName) => {
  try {
    if (!text) {
      ElMessage.warning('复制内容为空')
      return
    }
    
    // 使用现代浏览器的 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      ElMessage.success(`${fieldName}复制成功`)
    } else {
      // 降级方案：使用传统的 document.execCommand
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          ElMessage.success(`${fieldName}复制成功`)
        } else {
          ElMessage.error('复制失败')
        }
      } catch (err) {
        ElMessage.error('复制失败')
      }
      
      document.body.removeChild(textArea)
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.banking-receive-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-table__header-wrapper .cell) {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

/* 复制按钮样式 */
.copy-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.text-ellipsis {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.copy-btn {
  flex-shrink: 0;
  padding: 4px;
  margin: 0;
}

.copy-btn:hover {
  color: var(--el-color-primary);
}
:deep(.el-dialog) {
  max-height: 500px;
  overflow: auto;
}

/* 让表格滚动条始终显示 */
::v-deep(.el-table__body-wrapper .el-scrollbar__bar) {
  display: block!important;
}
:deep(.el-scrollbar__thumb) {
  background-color: #909399;
  opacity: 1;
}
</style>